// 文件用途：统一 HTTP 客户端封装（仅注释，不改逻辑）
// 核心要点：
// - 基于 @ohos/axios 创建实例，自动拼接 BASE_URL（见 util/serverConfig.js）
// - 从 globalThis.userId 注入 X-User-Id 请求头（用于后端识别当前用户）
// - 统一错误提取与拼接，便于排查：优先服务端返回文本/JSON message，其次异常 message
// - GET/DELETE 使用 params；POST/PUT 使用 data
import axios from '@ohos/axios'
import { BASE_URL } from './serverConfig'
const _axios = axios.create({
    baseURL: BASE_URL
})

// 通用请求方法
// - url: 相对路径（如 /user/login）
// - method: GET/POST/PUT/DELETE
// - params: 对于 GET/DELETE 作为 query，其余作为 body
// - callback: 成功回调（只传 response.data）
// - onError: 失败回调（传入拼装后的错误字符串）
export const request = (url, method, params, callback, onError) => {
    const cfg = { url, method };
    try {
        const glb = globalThis || {};
        const uid = glb && glb.userId != null ? glb.userId : undefined;
        const headers = {};
        if (uid != null && uid !== '') {
            headers['X-User-Id'] = String(uid);
        }
        cfg['headers'] = Object.assign({}, cfg['headers'] || {}, headers);
    } catch (e) {
        // ignore header injection errors
    }
    const m = (method || 'get').toLowerCase();
    if (m === 'get' || m === 'delete') {
        cfg['params'] = params;
    } else {
        cfg['data'] = params;
    }
    _axios(cfg).then(response => {
            callback && callback(response.data)
        }).catch(error => {
        let msg = 'HTTP error';
        let status = undefined;
            try {
                if (error && error.response) {
                    const resp = error.response;
            status = resp.status;
                    if (typeof resp.data === 'string') {
                        msg = resp.data;
                    } else if (resp.data && typeof resp.data.message === 'string') {
                        msg = resp.data.message;
                    } else if (error.message) {
                        msg = error.message;
                    }
                } else if (error && error.message) {
                    msg = error.message;
                }
            } catch (e) {
                // ignore
            }
        const methodStr = (method || 'GET').toUpperCase();
        const composed = `${status ? status + ' ' : ''}${msg} [${methodStr} ${url}]`;
        console.error('HTTP error:', composed);
        onError && onError(composed);
        })
}

export const get = (url, params, callback, onError) => {
    request(url, 'get', params, callback, onError)
}

export const post = (url, params, callback, onError) => {
    request(url, 'post', params, callback, onError)
}

export const put = (url, params, callback, onError) => {
    request(url, 'put', params, callback, onError)
}

export const del = (url, params, callback, onError) => {
    request(url, 'delete', params, callback, onError)
}